<template lang="pug">
  el-drawer.commonDrawer(
    :title="`${!id ? '添加' : '查看'}教保师`"
    :visible="visibleDialog"
    append-to-body
    center
    destroy-on-close
    :close-on-press-escape="false"
    :wrapperClosable="false"
    direction="rtl"
    size="1120px"
    @close="$_handleCancel"
  )
    .drawer-content
      basic-form(v-model="info" :avatarStyle="{ width: '240px', height: '240px' }" ref="basicForm" :disabled="disabled")
        section.panel
          h2 家庭情况
          edit-table(:column="familyColumn" v-model="families")
        section.panel
          h2 学习履历
          edit-table(:column="studyColumn" v-model="studies")
        //section.panel()
        //  h2 其他
        //  form-box.moreForm(
        //    ref="moreForm"
        //    :fields="moreField"
        //    :showBtns="false"
        //    :layoutCol="{ xs: 24, md: 24, lg: 24 }"
        //  )
        //    //- edit-table(:column="familyColumn" v-model="info.families" slot="form-family")
        //    template(slot="form-license")
        //      el-button(icon="el-icon-plus" @click="listChange('licenses', 0, 'add')") 增加
        //      el-row(:gutter="32")
        //        el-col.mt10(:span="12" v-for="(item, index) in licenses" :key="item.id")
        //          p
        //            el-input(v-model="licenses[index].value" style="width: 184px"  placeholder="证照名称")
        //            el-button.ml5(icon="el-icon-delete" circle @click="listChange('licenses', index, 'delete')")
        //          upload-file.mt10(:limit="1" accept="image/*" btnSize="small" @change="files => fileChange(files, 'licenses', index)")
        //    template(slot="form-bodyTest")
        //      el-button(icon="el-icon-plus" @click="listChange('bodyTests', 0, 'add')") 增加
        //      el-row(:gutter="32")
        //        el-col.mt10(:span="12" v-for="(item, index) in bodyTests" :key="item.id")
        //          p
        //            el-date-picker(v-model="bodyTests[index].date" style="width: 184px"  placeholder="选择时间")
        //            el-button.ml5(icon="el-icon-delete" circle @click="listChange('bodyTests', index, 'delete')")
        //          upload-file.mt10(:limit="1" accept="image/*" btnSize="small" @change="files => fileChange(files, 'bodyTests', index)")
        //    template(slot="form-vaccine")
        //      el-button(icon="el-icon-plus" @click="listChange('vaccines', 0, 'add')") 增加
        //      el-row(:gutter="32")
        //        el-col.mt10(:span="12" v-for="(item, index) in vaccines" :key="item.id")
        //          p
        //            el-date-picker(v-model="vaccines[index].date" style="width: 184px" placeholder="选择时间")
        //            el-button.ml5(icon="el-icon-delete" @click="listChange('vaccines', index, 'delete')")
        //          upload-file.mt10(:limit="1" accept="image/*" btnSize="small" @change="files => fileChange(files, 'vaccines', index)")
    .drawer-footer.tr
      el-button.gradientVertical(size="large" :loading="submitting" @click="submitHandle" round) 确定
</template>
<script>
import dayjs from 'dayjs'
import EditTable from '@/components/Basic/EditTable'
import { submitStaff } from '../../api'
import { familyColumn, studyColumn } from './config'
import { fileFormat, isEmpty } from '@/utils/util'
import TeachAreaModal from '@/components/Business/TeachAreaModal'
import BasicForm from './basicForm'

export default {
  components: {
    EditTable,
    TeachAreaModal,
    BasicForm
  },
  props: {
    id: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      default: () => ({})
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      submitting: false,
      info: {},
      familyColumn,
      studyColumn,
      families: [],
      studies: [],
      licenses: [], // 证照
      bodyTests: [], // 体检
      vaccines: [] // 疫苗
    }
  },
  computed: {
    visibleDialog: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    moreField () {
      const { info } = this
      return [
        // {
        //   label: '证照类型',
        //   key: 'licence',
        //   type: 'select',
        //   layoutCol: { xs: 12, md: 12, lg: 12 },
        //   options: [],
        //   initialValue: info.licence
        // },
        // {
        //   label: '证照',
        //   key: 'licenceFile',
        //   type: 'upload',
        //   fieldProps: {
        //     btnSize: 'small',
        //     imgFlag: true,
        //     limit: 1,
        //     accept: 'image/*',
        //     'show-file-list': false
        //   },
        //   initialValue: info.licenceUrl ? [{ url: info.licenceUrl }] : []
        // },
        {
          label: '证照',
          key: 'license',
          layoutCol: { xs: 24, md: 24, lg: 24 },
          type: 'slot'
        },
        {
          label: '体检情况',
          key: 'bodyTest',
          layoutCol: { xs: 24, md: 24, lg: 24 },
          type: 'slot'
        },
        {
          label: '疫苗情况',
          key: 'vaccine',
          layoutCol: { xs: 24, md: 24, lg: 24 },
          type: 'slot'
        },
        {
          label: '擅长科目',
          key: 'goodAtId',
          type: 'select',
          layoutCol: { xs: 12, md: 12, lg: 12 },
          fieldProps: {
            options: [
              { id: '英语', name: '英语' },
              { id: '语文', name: '语文' },
              { id: '数学', name: '数学' },
              { id: '计算机', name: '计算机' },
              { id: '绘画', name: '绘画' },
              { id: '-1', name: '其他' }
            ]
          },
          events: {
            change: val => this.formChange(val, 'subject')
          },
          initialValue: info.goodAtId
        },
        {
          label: '科目名称',
          key: 'goodAt',
          hidden: info.subject !== '-1',
          layoutCol: { xs: 12, md: 12, lg: 12 },
          fieldProps: {
            placeholder: '请输入擅长科目'
          },
          initialValue: info.goodAt
        },
        {
          label: '备注',
          key: 'remark',
          type: 'textarea',
          initialValue: info.remark
        }
      ]
    }
  },
  watch: {
    detail (val) {
      console.log(val)
      this.info = {
        ...val,
        headImgUrl: Array.isArray(val.headImgUrl) ? val.headImgUrl : (val.headImgUrl ? [{ url: val.headImgUrl }] : [])
      }
      // if (val.headImgUrl) {
      //   this.headImgUrl = [{ url: val.headImgUrl }]
      // }
      this.families = val.relations || []
      this.studies = val.careers || []
      this.bodyTests = val.healthies || []
      this.vaccines = val.vaccines || []
      this.licenses = val.licenses || []
    },
    visible (val) {
      if (val && !this.id) {
        this.info = {
          headImgUrl: []
        }
        this.families = []
        this.studies = []
        this.bodyTests = []
        this.vaccines = []
        this.licenses = []
      }
    }
  },
  created () {
  },
  methods: {
    formChange (val, key) {
      const { info } = this
      if (key === 'subject') {
        info[key] = val
        this.info = { ...info }
      }
    },
    listChange (key, index, type) {
      const list = this[key]
      if (type === 'add') {
        list.push({
          id: new Date().getTime().toString(),
          addFlag: true,
          date: '',
          value: '',
          files: []
        })
      }
      if (type === 'delete') {
        list.splice(index, 1)
      }
      this[key] = [...list]
    },
    fileChange (fileList, key, index) {
      const list = this[key]
      list[index] = {
        ...list[index],
        files: fileFormat(fileList)
      }
      console.log(list)
      this[key] = [...list]
    },
    // 提交
    async submitHandle () {
      // bodyTests, vaccines, licenses,
      const { families, studies, id: staffId } = this
      const { headImgUrl } = this.info

      let headImgUrlString = ''
      if (headImgUrl.length > 0) {
        headImgUrlString = fileFormat(headImgUrl)[0].url
      }
      console.log(headImgUrl)
      const values = await this.$refs.basicForm.$refs.basicForm.submitForm()

      if (isEmpty(values.birthday)) {
        delete values.birthday
      }
      if (isEmpty(values.fullAt)) {
        delete values.fullAt
      }
      if (isEmpty(values.joinAt)) {
        delete values.joinAt
      }

      console.log(values)
      const params = {
        ...values,
        headImgUrl: headImgUrlString,
        relations: families.map(x => {
          if (x.emergency) {
            x.emergency = x.emergency === '1'
          }
          if (x.addFlag) {
            delete x.id
          }
          delete x.action
          delete x.addFlag
          delete x.editFlag
          return x
        }),
        careers: studies.filter(x => Array.isArray(x.date) && x.date.length > 0).map(x => {
          x.beginDate = dayjs(x.date[0]).format('YYYY/MM/DD')
          x.endDate = dayjs(x.date[1]).format('YYYY/MM/DD')
          if (x.addFlag) {
            delete x.id
          }
          delete x.action
          delete x.addFlag
          delete x.editFlag
          return x
        })
      }

      // const moreValues = await this.$refs.moreForm.submitForm()
      // params = {
      //   ...params,
      //   ...moreValues,
      //   goodAt: moreValues.goodAt || moreValues.goodAtId,
      //   // 体检
      //   healthies: bodyTests.filter(x => x.date && x.files[0]).map(x => ({
      //     eventTime: dayjs(x.date).format('YYYY/MM/DD'),
      //     id: x.addFlag ? '' : x.id,
      //     resURL: x.files[0].url,
      //     resType: x.files[0].type
      //   })),
      //   // 证书
      //   licenses: licenses.filter(x => x.value && x.files[0]).map(x => ({
      //     licenseType: x.value,
      //     id: x.addFlag ? '' : x.id,
      //     resURL: x.files[0].url,
      //     resType: x.files[0].type
      //   })),
      //   // 疫苗
      //   vaccines: vaccines.filter(x => x.date && x.files[0]).map(x => ({
      //     eventTime: dayjs(x.date).format('YYYY/MM/DD'),
      //     id: x.addFlag ? '' : x.id,
      //     resURL: x.files[0].url,
      //     resType: x.files[0].type
      //   }))
      // }

      console.log(params)
      delete params.id
      this.submitting = true
      submitStaff({}, {
        staffId,
        ...params
      }, 'post').then(() => {
        this.$message.success('提交成功')
        this.$emit('getList')
        this.$_handleCancel()
      }).finally(() => {
        this.submitting = false
      })
    },
    $_handleCancel () {
      this.visibleDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.panel{
  > h2 {
    font-size: 18px;
    font-weight: bold;
    color: #333333;
    margin-bottom: 20px;
    margin-top: 0
  }

  + .panel{
    margin-top: 48px
  }
}

</style>
